﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Linq.Expressions;
using Atomic.Common.Validators;

namespace Atomic.Web.Handlers
{
    /// <summary>
    /// 一般处理程序基础，通过反射调用方法，继承后指出在一个IHttpHandler成员中同时定义很多参数为HttpContext的方法
    /// </summary>
    public abstract class BaseHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        object obj = new object();
        protected abstract Dictionary<string, Action<HttpContext>> Actions { get; }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string methodName = context.Request["method"];

            //不包含方法，则新建方法委托
            if (!Actions.ContainsKey(methodName))
            {
                lock (obj)
                {
                    MethodInfo methodInfo = this.GetType().GetMethod(methodName, new Type[] { typeof(HttpContext) });
                    ParameterExpression paramExp = Expression.Parameter(typeof(HttpContext));
                    MethodCallExpression callExp = Expression.Call(Expression.Constant(this), methodInfo, paramExp);
                    Expression<Action<HttpContext>> lambda = Expression.Lambda<Action<HttpContext>>(callExp, paramExp);
                    Action<HttpContext> action = lambda.Compile();
                    if (!Actions.ContainsKey(methodName))
                    {
                        Actions.Add(methodName, action);
                    }
                }
            }
            Actions[methodName](context);
        }

        /// <summary>
        /// 数据验证结果
        /// </summary>
        public ValidatedResult VResult { set; get; }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}